<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能客户关系管理助手</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        :root {
            --primary: #4361ee;
            --secondary: #3f37c9;
            --accent: #4895ef;
            --dark: #1e1e2c;
            --darker: #14141f;
            --light: #f8f9fa;
            --success: #4caf50;
            --warning: #ff9800;
            --danger: #f44336;
            --gray: #6c757d;
            --border-radius: 8px;
            --transition: all 0.3s ease;
        }

        body {
            background-color: var(--darker);
            color: var(--light);
            display: flex;
            min-height: 100vh;
        }

        /* 侧边栏样式 */
        .sidebar {
            width: 250px;
            background-color: var(--dark);
            padding: 20px 0;
            height: 100vh;
            position: fixed;
            transition: var(--transition);
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.2);
            z-index: 100;
        }

        .logo-container {
            display: flex;
            align-items: center;
            padding: 0 20px 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            margin-bottom: 20px;
        }

        .logo {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--accent), var(--primary));
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 10px;
        }

        .logo i {
            font-size: 20px;
        }

        .logo-text {
            font-size: 20px;
            font-weight: 700;
            background: linear-gradient(to right, var(--accent), var(--primary));
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
        }

        .nav-links {
            list-style: none;
            padding: 0 15px;
        }

        .nav-links li {
            margin-bottom: 5px;
        }

        .nav-links a {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            text-decoration: none;
            color: rgba(255, 255, 255, 0.7);
            border-radius: var(--border-radius);
            transition: var(--transition);
        }

        .nav-links a:hover, .nav-links a.active {
            background-color: rgba(67, 97, 238, 0.2);
            color: var(--light);
        }

        .nav-links a i {
            margin-right: 10px;
            width: 20px;
            text-align: center;
        }

        /* 主内容区样式 */
        .main-content {
            flex: 1;
            margin-left: 250px;
            padding: 20px;
            transition: var(--transition);
        }

        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 30px;
            padding-bottom: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .page-title {
            font-size: 24px;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .page-title i {
            margin-right: 10px;
            color: var(--accent);
        }

        .user-actions {
            display: flex;
            align-items: center;
            gap: 15px;
        }

        .user-id-input {
            display: flex;
            gap: 10px;
            align-items: center;
            background-color: rgba(255, 255, 255, 0.08);
            padding: 8px 15px;
            border-radius: 30px;
        }

        .user-id-input input {
            background: transparent;
            border: none;
            color: white;
            font-size: 14px;
            width: 120px;
        }

        .user-id-input input::placeholder {
            color: rgba(255, 255, 255, 0.6);
        }

        .user-id-input button {
            background: var(--primary);
            border: none;
            color: white;
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 12px;
            cursor: pointer;
        }

        .search-box {
            position: relative;
        }

        .search-box input {
            background-color: rgba(255, 255, 255, 0.08);
            border: none;
            padding: 10px 15px 10px 40px;
            border-radius: 30px;
            color: var(--light);
            width: 250px;
            transition: var(--transition);
        }

        .search-box input:focus {
            outline: none;
            background-color: rgba(255, 255, 255, 0.15);
            width: 300px;
        }

        .search-box i {
            position: absolute;
            left: 15px;
            top: 50%;
            transform: translateY(-50%);
            color: rgba(255, 255, 255, 0.5);
        }

        .user-profile {
            display: flex;
            align-items: center;
            background-color: rgba(255, 255, 255, 0.08);
            padding: 8px 15px;
            border-radius: 30px;
            cursor: pointer;
            transition: var(--transition);
        }

        .user-profile:hover {
            background-color: rgba(255, 255, 255, 0.15);
        }

        .user-profile img {
            width: 32px;
            height: 32px;
            border-radius: 50%;
            margin-right: 10px;
            object-fit: cover;
        }

        /* 卡片样式 */
        .card {
            background-color: var(--dark);
            border-radius: var(--border-radius);
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
            margin-bottom: 25px;
            overflow: hidden;
        }

        .card-header {
            padding: 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }

        .card-title {
            font-size: 18px;
            font-weight: 600;
        }

        .card-body {
            padding: 20px;
        }

        /* 智能助手区域 */
        .assistant-container {
            display: flex;
            flex-direction: column;
            height: 500px;
            background-color: rgba(255, 255, 255, 0.05);
            border-radius: var(--border-radius);
            overflow: hidden;
        }

        .assistant-header {
            padding: 15px 20px;
            background-color: rgba(67, 97, 238, 0.2);
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .assistant-header i {
            font-size: 20px;
            margin-right: 10px;
            color: var(--accent);
        }

        .assistant-messages {
            flex: 1;
            padding: 20px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            gap: 15px;
        }

        .message {
            max-width: 80%;
            padding: 12px 18px;
            border-radius: 18px;
            line-height: 1.5;
            position: relative;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .user-message {
            background-color: var(--primary);
            align-self: flex-end;
            border-bottom-right-radius: 5px;
        }

        .ai-message {
            background-color: rgba(255, 255, 255, 0.1);
            align-self: flex-start;
            border-bottom-left-radius: 5px;
        }

        .message-time {
            font-size: 11px;
            opacity: 0.7;
            margin-top: 5px;
            text-align: right;
        }

        .assistant-input {
            display: flex;
            padding: 15px;
            background-color: rgba(255, 255, 255, 0.05);
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }

        .assistant-input input {
            flex: 1;
            padding: 12px 15px;
            background-color: rgba(255, 255, 255, 0.08);
            border: none;
            border-radius: 30px;
            color: var(--light);
            margin-right: 10px;
        }

        .assistant-input input:focus {
            outline: none;
            background-color: rgba(255, 255, 255, 0.12);
        }

        /* 功能卡片样式 */
        .function-cards {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .function-card {
            background-color: var(--dark);
            border-radius: var(--border-radius);
            padding: 20px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }

        .function-card-header {
            display: flex;
            align-items: center;
            margin-bottom: 20px;
        }

        .function-card-icon {
            width: 40px;
            height: 40px;
            background: linear-gradient(135deg, var(--accent), var(--primary));
            border-radius: 10px;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-right: 12px;
        }

        .function-card-title {
            font-size: 18px;
            font-weight: 600;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-size: 14px;
            opacity: 0.9;
        }

        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 12px 15px;
            background-color: rgba(255, 255, 255, 0.08);
            border: none;
            border-radius: var(--border-radius);
            color: var(--light);
        }

        .form-group textarea {
            height: 150px;
            resize: vertical;
        }

        .result-area {
            background-color: rgba(255, 255, 255, 0.05);
            border-radius: var(--border-radius);
            padding: 15px;
            margin-top: 20px;
            max-height: 250px;
            overflow-y: auto;
        }

        .result-title {
            font-size: 15px;
            margin-bottom: 10px;
            color: var(--accent);
        }

        /* 按钮样式 */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 10px 20px;
            border-radius: var(--border-radius);
            border: none;
            cursor: pointer;
            font-weight: 500;
            transition: var(--transition);
        }

        .btn i {
            margin-right: 8px;
        }

        .btn-sm {
            padding: 6px 12px;
            font-size: 13px;
        }

        .btn-primary {
            background-color: var(--primary);
            color: white;
        }

        .btn-primary:hover {
            background-color: var(--secondary);
        }

        .btn-success {
            background-color: var(--success);
            color: white;
        }

        .btn-warning {
            background-color: var(--warning);
            color: white;
        }

        .btn-danger {
            background-color: var(--danger);
            color: white;
        }

        .btn-outline {
            background-color: transparent;
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: rgba(255, 255, 255, 0.7);
        }

        .btn-outline:hover {
            background-color: rgba(255, 255, 255, 0.1);
            color: var(--light);
        }

        .loading {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .spinner {
            width: 24px;
            height: 24px;
            border: 3px solid rgba(255, 255, 255, 0.3);
            border-radius: 50%;
            border-top-color: var(--accent);
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 响应式设计 */
        @media (max-width: 992px) {
            .sidebar {
                width: 80px;
            }

            .logo-text, .link-text {
                display: none;
            }

            .nav-links a {
                justify-content: center;
            }

            .nav-links a i {
                margin-right: 0;
                font-size: 20px;
            }

            .main-content {
                margin-left: 80px;
            }

            .function-cards {
                grid-template-columns: 1fr;
            }
        }

        @media (max-width: 768px) {
            .search-box input {
                width: 150px;
            }

            .search-box input:focus {
                width: 180px;
            }

            .header {
                flex-direction: column;
                align-items: flex-start;
                gap: 15px;
            }

            .user-actions {
                width: 100%;
                justify-content: space-between;
            }
        }
        /* 添加历史记录弹窗样式 */
        .history-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.7);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
        }

        .history-content {
            width: 80%;
            max-width: 800px;
            background-color: var(--dark);
            border-radius: var(--border-radius);
            overflow: hidden;
            display: flex;
            flex-direction: column;
            max-height: 80vh;
        }

        .history-header {
            padding: 15px 20px;
            background-color: rgba(67, 97, 238, 0.2);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .history-title {
            font-size: 18px;
            font-weight: 600;
        }

        .history-close {
            background: none;
            border: none;
            color: var(--light);
            font-size: 20px;
            cursor: pointer;
        }

        .history-list {
            flex: 1;
            overflow-y: auto;
            padding: 15px;
        }

        .history-item {
            padding: 15px;
            margin-bottom: 10px;
            background-color: rgba(255, 255, 255, 0.05);
            border-radius: var(--border-radius);
            cursor: pointer;
            transition: var(--transition);
        }

        .history-item:hover {
            background-color: rgba(67, 97, 238, 0.2);
        }

        .history-item-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 8px;
        }

        .history-item-title {
            font-weight: 600;
            color: var(--accent);
        }

        .history-item-date {
            font-size: 12px;
            opacity: 0.7;
        }

        .history-item-content {
            font-size: 14px;
            opacity: 0.9;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .history-footer {
            padding: 15px;
            display: flex;
            justify-content: flex-end;
            border-top: 1px solid rgba(255, 255, 255, 0.1);
        }
    </style>
</head>
<body>
<!-- 侧边导航 -->
<div class="sidebar">
    <div class="logo-container">
        <div class="logo">
            <i class="fas fa-brain"></i>
        </div>
        <div class="logo-text">智能CRM</div>
    </div>

    <ul class="nav-links">
        <li><a href="#" class="active"><i class="fas fa-home"></i> <span class="link-text">AI助手</span></a></li>
        <li><a href="/customer"><i class="fas fa-users"></i> <span class="link-text">客户管理</span></a></li>
        <li><a href="/base_dict"><i class="fas fa-book"></i> <span class="link-text">数据字典</span></a></li>
        <li><a href="/usermanage"><i class="fas fa-user-cog"></i> <span class="link-text">用户管理</span></a></li>
        <li><a href="/product"><i class="fas fa-box"></i> <span class="link-text">产品管理</span></a></li>
        <li><a href="/orderitems"><i class="fas fa-shopping-cart"></i> <span class="link-text">订单管理</span></a></li>
    </ul>
</div>

<!-- 主内容区 -->
<div class="main-content" id="app">
    <!-- 头部区域 -->
    <div class="header">
        <div class="page-title">
            <i class="fas fa-robot"></i> AI智能助手控制台
        </div>

        <div class="user-actions">
            <div class="search-box">
                <i class="fas fa-search"></i>
                <input type="text" placeholder="搜索功能...">
            </div>

            <div class="user-profile">
                <img src="https://randomuser.me/api/portraits/men/32.jpg" alt="用户头像">
                <span th:text="${session.username}"></span>
            </div>
        </div>
    </div>

    <!-- 智能小助手卡片 -->
    <div class="card">
        <div class="card-header">
            <div class="card-title">
                <i class="fas fa-robot"></i> AI智能小助手
            </div>
            <div>
                <button class="btn btn-outline" @click="showHistory">
                    <i class="fas fa-history"></i> 历史记录
                </button>
                <button class="btn btn-outline" @click="clearHistory">
                    <i class="fas fa-trash"></i> 清除历史
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="assistant-container">
                <div class="assistant-header">
                    <div>
                        <i class="fas fa-robot"></i>
                        <span>DeepSeek AI助手 - 为您提供智能客户交流服务</span>
                    </div>
                    <div v-if="isTyping" class="loading">
                        <div class="spinner"></div>
                        <span>思考中...</span>
                    </div>
                </div>

                <div class="assistant-messages" ref="messagesContainer">
                    <div class="message ai-message" v-if="messages.length === 0">
                        您好！我是您的AI助手，可以帮助您生成与客户沟通的内容模板、分析客户对话并提供建议。请告诉我您的需求。
                    </div>

                    <div v-for="(msg, index) in messages" :key="index"
                         :class="['message', msg.role === 'user' ? 'user-message' : 'ai-message']">
                        <div v-html="msg.content"></div>
                        <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
                    </div>
                </div>

                <div class="assistant-input">
                    <input type="text" v-model="userInput" placeholder="输入您需要AI助手帮助的内容..."
                           @keyup.enter="sendMessage" :disabled="isTyping">
                    <button class="btn btn-primary" @click="sendMessage" :disabled="isTyping">
                        <i class="fas fa-paper-plane"></i> 发送
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- 功能卡片区域 -->
    <div class="function-cards">
        <!-- 模板生成卡片 -->
        <div class="function-card">
            <div class="function-card-header">
                <div class="function-card-icon">
                    <i class="fas fa-file-alt"></i>
                </div>
                <div class="function-card-title">模板生成器</div>
            </div>

            <div class="form-group">
                <label>模板类型</label>
                <select v-model="templateType">
                    <option v-for="(type, index) in templateTypes" :key="index" :value="type">{{ type }}</option>
                </select>
            </div>

            <div class="form-group">
                <label>客户姓名</label>
                <input type="text" v-model="customerName" placeholder="请输入客户姓名">
            </div>

            <div class="form-group">
                <label>产品名称</label>
                <input type="text" v-model="productName" placeholder="请输入产品名称">
            </div>

            <div class="form-group">
                <label>公司名称</label>
                <input type="text" v-model="companyName" placeholder="请输入公司名称">
            </div>

            <button class="btn btn-primary" @click="generateTemplate" :disabled="isGenerating">
                <i class="fas fa-magic"></i> 生成模板
            </button>

            <div class="result-area" v-if="generatedTemplate">
                <div class="result-title">生成的模板：</div>
                <div v-html="generatedTemplate"></div>
            </div>
        </div>

        <!-- 对话分析卡片 -->
        <div class="function-card">
            <div class="function-card-header">
                <div class="function-card-icon">
                    <i class="fas fa-chart-line"></i>
                </div>
                <div class="function-card-title">对话分析器</div>
            </div>

            <div class="form-group">
                <label>客户对话内容</label>
                <textarea v-model="conversationText" placeholder="请输入客户对话内容..."></textarea>
            </div>

            <button class="btn btn-primary" @click="analyzeConversation" :disabled="isAnalyzing">
                <i class="fas fa-search"></i> 分析对话
            </button>

            <div class="result-area" v-if="analysisResult">
                <div class="result-title">分析结果：</div>
                <div v-html="analysisResult"></div>
            </div>
        </div>
    </div>

    <!-- 历史记录弹窗 -->
    <div class="history-modal" v-if="showHistoryModal">
        <div class="history-content">
            <div class="history-header">
                <div class="history-title">
                    <i class="fas fa-history"></i> 对话历史记录
                </div>
                <button class="history-close" @click="showHistoryModal = false">
                    <i class="fas fa-times"></i>
                </button>
            </div>

            <div class="history-list">
                <div v-if="historyLoading" class="loading">
                    <div class="spinner"></div>
                    <span>加载中...</span>
                </div>

                <div v-else>
                    <div v-if="historySessions.length === 0" class="history-item">
                        <div class="history-item-content">暂无历史记录</div>
                    </div>

                    <div v-for="(session, index) in historySessions" :key="index"
                         class="history-item" @click="loadSessionHistory(session.sessionId)">
                        <div class="history-item-header">
                            <div class="history-item-title">会话 {{ index + 1 }}</div>
                            <div class="history-item-date">{{ formatDate(session.startTime) }}</div>
                        </div>
                        <div class="history-item-content">
                            {{ session.firstMessage || '无消息内容' }}...
                        </div>
                    </div>
                </div>
            </div>

            <div class="history-footer">
                <button class="btn btn-outline" @click="showHistoryModal = false">
                    关闭
                </button>
            </div>
        </div>
    </div>
</div>

<script>
    new Vue({
        el: '#app',
        data: {
            userId: 'user_' + Math.floor(Math.random() * 1000),
            userInput: '',
            messages: [],
            isTyping: false,
            showHistoryModal: false,
            historySessions: [],
            historyLoading: false,
            currentSessionId: null,

            // 模板生成相关数据
            templateTypes: [],
            templateType: '产品介绍',
            customerName: '',
            productName: '',
            companyName: '',
            generatedTemplate: '',
            isGenerating: false,

            // 对话分析相关数据
            conversationText: '',
            analysisResult: '',
            isAnalyzing: false
        },
        mounted() {
            this.loadTemplateTypes();
            this.loadHistory();
        },
        methods: {
            setUserId() {
                if (!this.userId) {
                    alert('请输入用户ID');
                    return;
                }
                this.loadHistory();
            },

            // 显示历史记录弹窗
            async showHistory() {
                this.showHistoryModal = true;
                this.historyLoading = true;

                try {
                    // 使用axios获取用户的所有会话记录
                    const response = await axios.get(`/api/assistant/history/${this.userId}`);

                    if (response.data.success) {
                        // 将会话分组
                        this.historySessions = this.groupSessions(response.data.history);
                    }
                } catch (error) {
                    console.error('加载历史记录失败:', error);
                    alert('加载历史记录失败，请稍后再试');
                } finally {
                    this.historyLoading = false;
                }
            },

            // 将历史记录分组为会话
            groupSessions(history) {
                if (!history || history.length === 0) return [];

                const sessions = [];
                let currentSession = [];
                let sessionStartTime = null;

                // 按时间顺序处理消息
                history.forEach((msg, index) => {
                    // 跳过系统消息
                    if (msg.role === 'system') return;

                    const msgTime = new Date(msg.timestamp || Date.now());

                    if (currentSession.length === 0) {
                        // 新会话开始
                        sessionStartTime = msgTime;
                        currentSession.push(msg);
                    } else {
                        // 检查时间间隔（30分钟）
                        const lastMsgTime = new Date(currentSession[currentSession.length - 1].timestamp || Date.now());
                        const timeDiff = (msgTime - lastMsgTime) / (1000 * 60); // 分钟

                        if (timeDiff > 30) {
                            // 超过30分钟，创建新会话
                            sessions.push(this.createSession(currentSession, sessionStartTime));
                            currentSession = [msg];
                            sessionStartTime = msgTime;
                        } else {
                            // 继续当前会话
                            currentSession.push(msg);
                        }
                    }
                });

                // 添加最后一个会话
                if (currentSession.length > 0) {
                    sessions.push(this.createSession(currentSession, sessionStartTime));
                }

                // 按时间倒序排列（最新会话在前）
                return sessions.sort((a, b) => new Date(b.startTime) - new Date(a.startTime));
            },

            // 创建会话对象
            createSession(messages, startTime) {
                return {
                    sessionId: Date.now() + Math.random().toString(36).substr(2, 5),
                    messages: [...messages],
                    startTime: startTime,
                    firstMessage: messages[0]?.content?.substring(0, 100) || '新会话'
                };
            },

            // 加载特定会话的历史记录
            async loadSessionHistory(sessionId) {
                try {
                    // 使用axios获取完整历史记录
                    const response = await axios.get(`/api/assistant/history/${this.userId}`);

                    if (response.data.success) {
                        // 过滤出当前会话的消息
                        const sessions = this.groupSessions(response.data.history);
                        const session = sessions.find(s => s.sessionId === sessionId);

                        if (session) {
                            // 过滤掉系统消息并显示
                            this.messages = session.messages
                                .filter(msg => msg.role !== 'system')
                                .map(msg => ({
                                    role: msg.role,
                                    content: msg.content,
                                    timestamp: new Date(msg.timestamp || Date.now())
                                }));

                            this.scrollToBottom();
                            this.showHistoryModal = false;
                        }
                    }
                } catch (error) {
                    console.error('加载会话历史失败:', error);
                    alert('加载会话历史失败，请稍后再试');
                }
            },

            // 与AI助手对话
            async sendMessage() {
                if (!this.userInput.trim() || !this.userId) return;

                const userMessage = {
                    role: 'user',
                    content: this.userInput,
                    timestamp: new Date()
                };

                // 先添加到本地，以显示即时反馈
                this.messages.push(userMessage);
                this.userInput = '';
                this.scrollToBottom();

                this.isTyping = true;

                try {
                    // 使用axios发送消息
                    const response = await axios.post('/api/assistant/chat', {
                        userId: this.userId,
                        message: userMessage.content,
                        newConversation: false // 我们总是继续当前会话
                    });

                    if (response.data.success) {
                        const aiMessage = {
                            role: 'assistant',
                            content: response.data.message,
                            timestamp: new Date()
                        };
                        this.messages.push(aiMessage);
                    } else {
                        this.messages.push({
                            role: 'assistant',
                            content: '抱歉，处理请求时出错: ' + response.data.error,
                            timestamp: new Date()
                        });
                    }
                } catch (error) {
                    console.error('发送消息失败:', error);
                    this.messages.push({
                        role: 'assistant',
                        content: '网络错误，请稍后再试',
                        timestamp: new Date()
                    });
                } finally {
                    this.isTyping = false;
                    this.scrollToBottom();
                }
            },

            // 获取对话历史
            async loadHistory() {
                if (!this.userId) return;

                try {
                    // 使用axios获取历史记录
                    const response = await axios.get(`/api/assistant/history/${this.userId}`);

                    if (response.data.success) {
                        // 过滤掉系统消息并显示
                        this.messages = response.data.history
                            .filter(msg => msg.role !== 'system')
                            .map(msg => ({
                                role: msg.role,
                                content: msg.content,
                                timestamp: new Date(msg.timestamp || Date.now())
                            }));

                        this.scrollToBottom();
                    }
                } catch (error) {
                    console.error('加载历史失败:', error);
                }
            },

            // 清除对话历史
            async clearHistory() {
                if (!this.userId) return;

                if (!confirm('确定要清除当前用户的所有对话历史吗？此操作不可恢复。')) {
                    return;
                }

                try {
                    // 使用axios删除历史记录
                    const response = await axios.delete(`/api/assistant/history/${this.userId}`);

                    if (response.data.success) {
                        this.messages = [];
                        this.historySessions = [];
                        alert('对话历史已清除');
                    }
                } catch (error) {
                    console.error('清除历史失败:', error);
                    alert('清除历史记录失败，请稍后再试');
                }
            },

            // 获取模板类型
            async loadTemplateTypes() {
                try {
                    // 使用axios获取模板类型
                    const response = await axios.get('/api/assistant/template-types');

                    if (response.data.success) {
                        this.templateTypes = response.data.templates;
                    } else {
                        // 默认模板类型
                        this.templateTypes = [
                            '产品介绍', '客户跟进', '问题解决', '促销活动', '满意度调查',
                            '续约提醒', 'VIP专属优惠', '节假日问候', '投诉处理', '合同续签'
                        ];
                    }
                } catch (error) {
                    console.error('加载模板类型失败:', error);
                    // 默认模板类型
                    this.templateTypes = [
                        '产品介绍', '客户跟进', '问题解决', '促销活动', '满意度调查'
                    ];
                }
            },

            // 生成模板
            async generateTemplate() {
                if (!this.templateType) {
                    alert('请选择模板类型');
                    return;
                }

                this.isGenerating = true;

                try {
                    // 使用axios生成模板
                    const response = await axios.post('/api/assistant/generate-template', {
                        templateType: this.templateType,
                        customerName: this.customerName,
                        productName: this.productName,
                        companyName: this.companyName
                    });

                    if (response.data.success) {
                        this.generatedTemplate = response.data.template;
                    } else {
                        this.generatedTemplate = '无法生成模板: ' + response.data.error;
                    }
                } catch (error) {
                    console.error('生成模板失败:', error);
                    this.generatedTemplate = '网络错误，请稍后再试';
                } finally {
                    this.isGenerating = false;
                }
            },

            // 分析对话
            async analyzeConversation() {
                if (!this.conversationText.trim()) {
                    alert('请输入对话内容');
                    return;
                }

                this.isAnalyzing = true;

                try {
                    // 使用axios分析对话
                    const response = await axios.post('/api/assistant/analyze-conversation', {
                        conversation: this.conversationText
                    });

                    if (response.data.success) {
                        this.analysisResult = response.data.analysis;
                    } else {
                        this.analysisResult = '分析失败: ' + response.data.error;
                    }
                } catch (error) {
                    console.error('分析对话失败:', error);
                    this.analysisResult = '网络错误，请稍后再试';
                } finally {
                    this.isAnalyzing = false;
                }
            },

            // 辅助方法
            scrollToBottom() {
                this.$nextTick(() => {
                    const container = this.$refs.messagesContainer;
                    if (container) {
                        container.scrollTop = container.scrollHeight;
                    }
                });
            },

            formatTime(date) {
                return date.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'});
            },

            formatDate(date) {
                return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
            }
        }
    });
</script>
</body>
</html>